<template>
  <div class="login-container" style="background: url('src/assets/images/login-bg.svg') no-repeat center center fixed; background-size: cover;">
    <div class="login-box">
      <h2 class="title">小区物业管理系统</h2>
      <h3 class="title">LOGIN</h3>
      <div class="form-container">
        <div class="form-item">
          <input type="text" v-model="username" placeholder="请输入用户名" class="input-box">
        </div>
        <div class="form-item">
          <input type="password" v-model="password" placeholder="请输入密码" class="input-box">
        </div>
        <div class="role-container">
          <span>角色</span>
          <label><input type="radio" v-model="role" value="admin">管理员</label>
          <label><input type="radio" v-model="role" value="owner">业主</label>
          <label><input type="radio" v-model="role" value="property">物业</label>
        </div>
        <button class="login-btn" @click="handleLogin">登录</button>
      </div>
    </div>
    <!-- 登录页底部版权 -->
    <div class="footer">
      <el-text size="small" class="">
        Copyright © 2021 - 2025 物业管理 All Rights Reserved.
      </el-text>
    </div>

  </div>
</template>

<script>
import axios from 'axios'; // 引入 axios
import router from "@/router/index.js";
import { ElMessage } from 'element-plus'; // 引入 Element Plus 的消息提示组件

export default {
  data() {
    return {
      username: '',
      password: '',
      role: 'admin'
    };
  },
  methods: {
    async handleLogin() {
      try {
        let response;
        const apiUrl = this.role === 'admin'
            ? '/api/administrators/login'
            : '/api/users/login';

        const params = {
          account: this.username,
          password: this.password
        };

        // 修改请求参数传递方式
        response = await axios.post(apiUrl, null, { params });

        if (response && response.data.code === 200) {
          const token = response.data.token;
          localStorage.setItem('token', token);
          const userId = this.getTokenUserId(token);
          if (this.role === 'admin') {
            localStorage.setItem('adminName', this.username);
            router.push('/admin');
            ElMessage.success('成功跳转到管理员页面');
            console.log(userId+'跳转到管理员页面');
          } else {
            const personalInfoResponse = await axios.get('/api/users/personal', { params });
            console.log(personalInfoResponse);
            const userName = personalInfoResponse.data.data.name;
            console.log(userName);
            localStorage.setItem("userName", userName);
            const userType = this.getTokenUserType(token);
            if (userType === null) {
              ElMessage.error('解析用户角色信息失败，请重新登录');
              localStorage.removeItem('token');
              return;
            }
            if (this.role === 'owner' && userType === 1) {
              router.push('/owner');
              ElMessage.success('成功跳转到业主页面');
              console.log(userId+'跳转到业主页面');
            } else if (this.role === 'property' && userType === 2) {
              router.push('/property');
              ElMessage.success('成功跳转到物业页面');
              console.log(userId+'跳转到物业页面');
            } else {
              ElMessage.error('登录失败：角色不匹配');
              localStorage.removeItem('token');
            }
          }
        } else {
          ElMessage.error('登录失败：用户名或密码错误');
          console.log('登录失败：用户名或密码错误');
        }
      } catch (error) {
        ElMessage.error('请求出错，请稍后重试');
        console.error('请求出错：', error);
      }
    },
    getTokenUserType(token) {
      try {
        const payloadBase64 = token.split('.')[1];
        const decodedPayload = atob(payloadBase64);
        const payload = JSON.parse(decodedPayload);
        return payload.role;
      } catch (error) {
        console.error('解析 token 出错：', error);
        return null;
      }
    },
    getTokenUserId(token) {
      try {
        const payloadBase64 = token.split('.')[1];
        const decodedPayload = atob(payloadBase64);
        const payload = JSON.parse(decodedPayload);
        return payload.userId;
      } catch (error) {
        console.error('解析 token 出错：', error);
        return null;
      }
    }
  }
};
</script>

<style scoped>
.footer {
  position: fixed; /* 固定定位 */
  bottom: 0; /* 置于底部 */
  width: 100%; /* 宽度占满整个屏幕 */
  text-align: center; /* 文本居中 */
  background-color: #f5f5f5; /* 背景颜色，可根据需要修改 */
  padding: 10px 0; /* 上下内边距 */
}


.login-container {
  height: 90%;
  width: 100%;
  display: flex;
  flex-direction: column; /* 修改为垂直排列 */
  justify-content: center;
  align-items: center;
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: 100% 100%;
}


.login-box {
  background: rgba(255, 255, 255, 0.8);
  padding: 20px 30px;
  border-radius: 8px;
  height: 45%;
  width: 25%;
}

.title {
  color: #333;
  text-align: center;
  margin-bottom: 20px;
}

.form-container {
  display: flex;
  flex-direction: column;
  align-items: center; /* 水平居中 */
  justify-content: flex-end; /* 垂直对齐到容器底部 */
  margin-top: 10px;
  gap: 30px;
  height: 60%; /* 确保容器有高度，否则无法对齐到底部 */
  width: 100%;
}


.form-item {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
}

.input-box {
  width: 100%;
  height: 36px;
  padding: 0 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

.role-container {
  display: flex;
  align-items: center;
  gap: 30px;
}

.role-container label {
  display: flex;
  align-items: center;
  gap: 5px;
}

.role-container input[type="radio"] {
  -webkit-appearance: none;
  appearance: none;
  width: 16px;
  height: 16px;
  border: 2px solid #aacce4;
  border-radius: 50%;
  outline: none;
  cursor: pointer;
}

.role-container input[type="radio"]:checked {
  background-color: #3f7ffd;
  border: 2px solid #8fc4ff;
}

.login-btn {
  height: 40px;
  padding: 5px;
  background-color: #3f7ffd;
  color: #ffffff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  width: 100%;
}
</style>